import json
import requests
import lxml.html


def cas_Login(arrInput):
    CALLBACK_URL = arrInput['callback_url']
    LOGIN_URL = "https://"
    cas_data = {
        'username' : arrInput['username'],
        'password' : arrInput['password'],
    }
    cas_header = {
        "Accept": "text/html, application/xhtml+xml, image/jxr, */*",
        "Accept-Encoding": "gzip, deflate, br",
        "Accept-Language": "en-US, en; q=0.8, zh-Hans-CN; q=0.5, zh-Hans; q=0.3",
        "Cache-Control": "no-cache",
        "Connection": "keep-alive",
        "Content-Length": "156",
        "Content-Type": "application/x-www-form-urlencoded",
        "Referer": CALLBACK_URL,
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:63.0) Gecko/20100101 Firefox/63.0"
    }

    http_request = requests.session()
    http_response = http_request.get(CALLBACK_URL)
    html_content = http_response.text

    # parsing page for hidden inputs
    login_html = lxml.html.fromstring(html_content)
    hidden_inputs = login_html.xpath('//input[@type="hidden"]')
    user_form = {x.attrib["name"]: x.attrib["value"] for x in hidden_inputs}
    user_form["username"] = cas_data['username']
    user_form["password"] = cas_data['password']
    http_request.post(LOGIN_URL, data=user_form, headers=cas_header)
    http_request.get(CALLBACK_URL)
    cookies = http_request.cookies.get_dict()

    return cookies

def ips_Login(arrInput):
    """
    ips登录
    """
    LOGIN_URL = "https://"
    try:
        ips_data = {
            'username' : arrInput['username'],
            'password' : arrInput['password'],
            'sid' : arrInput['sid'],
            'service' : arrInput['service']
        }
    except:
        return {}
    http_request = requests.session()
    http_response =  http_request.post(LOGIN_URL, data=ips_data)
    try:
        resp = json.loads(http_response.text)
        CALLBACK_URL = resp["data"]["callback"]
        http_request.get(CALLBACK_URL)
        cookies = http_request.cookies.get_dict()
    except:
        return {}
    #print(cookies)
    return cookies
